package top.huntwolf.admin.common.typeHandler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import top.huntwolf.admin.common.enums.BookConditionEnum;
import top.huntwolf.admin.common.enums.EnumValue;
import top.huntwolf.admin.common.enums.OrderStatus;
import top.huntwolf.admin.common.enums.OrderType;
import top.huntwolf.admin.utils.GenericUtil;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@MappedTypes({OrderStatus.class, OrderType.class, BookConditionEnum.class})
public class EnumTypeHandler<T extends Enum<T> & EnumValue> extends BaseTypeHandler<T> {

    private final Class<T> type;

    //只能由子类调用
    protected EnumTypeHandler() {
        type = GenericUtil.getSuperClassGenericClass(getClass());
    }

    //由Mybatis根据类型动态生成实例
    public EnumTypeHandler(Class<T> type) {
        this.type = type;
    }

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, T t, JdbcType jdbcType) throws SQLException {
        Object value = t.toValue();
        if (jdbcType == null){
            preparedStatement.setObject(i,value);
        }else {
            preparedStatement.setObject(i,value,jdbcType.TYPE_CODE);
        }
    }

    @Override
    public T getNullableResult(ResultSet resultSet, String s) throws SQLException {
        return valueOf(resultSet.getString(s));
    }

    @Override
    public T getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return valueOf(resultSet.getString(i));
    }

    @Override
    public T getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return valueOf(callableStatement.getString(i));
    }

    private T valueOf(String s){
        return s == null?null:EnumValue.valueOf(type,s);
    }
}
